#include "moveitemtool.h"
#include "view/scene.h"
#include "item/item.h"
#include "command/movecommand.h"

#include <QGraphicsSceneMouseEvent>

namespace SymbolEditor
{

    MoveItemTool::MoveItemTool(QObject *parent):
        AbstractTool (parent),
        m_state(WaitForActivation)
    {
        setLabel("<b>M</b>ove items");
        setShortcut(QKeySequence("e,m"));
        setIcon(QIcon::fromTheme("transform-move"));
        updateAction();
    }

    void MoveItemTool::activate(Scene *scene)
    {
        if (m_state != WaitForActivation)
        {
            desactivate();
        }
        // FIXME: auto-desactivate if no selected items
        setScene(scene);
        m_state = WaitForOrigin;
    }

    void MoveItemTool::desactivate()
    {
        switch (m_state)
        {
            case WaitForActivation:
                break;
            case WaitForOrigin:
                break;
            case WaitForDestination:
                m_items.clear();
                break;
        }
        setScene(nullptr);
    }

    void MoveItemTool::pushCommand()
    {
        auto delta = m_destination - m_origin;
        auto command = new TranslateCommand;
        for (auto item : m_items)
        {
            // FIXME
            command->itemIdList << item->data(0).value<quint64>();
        }
        command->amount = delta;
        appendCommand(command);
    }

    bool MoveItemTool::mouseClickEvent(QGraphicsSceneMouseEvent *event)
    {
        switch (m_state)
        {
            case WaitForActivation:
                break;
            case WaitForOrigin:
            {
                m_items = scene()->selectedItems();
                m_origin = m_destination = event->scenePos();
                m_state = WaitForDestination;
                break;
            }
            case WaitForDestination:
            {
                // FIXME: Don't push command if translation is null
                m_destination = event->scenePos();
                pushCommand();
                // FIXME: auto-desactivate
                m_state = WaitForOrigin;
                break;
            }
        }
        return true;
    }

    void MoveItemTool::moveItems(const QPointF &pos)
    {
        auto delta = pos - m_destination;
        for (auto item: m_items)
        {
            item->moveBy(delta.x(), delta.y());
        }
        m_destination = pos;
    }

    bool MoveItemTool::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
    {
        switch (m_state)
        {
            case WaitForActivation:
                break;
            case WaitForOrigin:
                break;
            case WaitForDestination:
            {
                moveItems(event->scenePos());
                break;
            }
        }
        return true;
    }
}
